import axios from 'axios';
import {getBasicInfo} from './mixin';

const toolOptions = [
	['bold', 'italic', 'underline', 'blockquote'],
	[{
		header: 1
	}, {
		header: 2
	}],
	[{
		list: 'ordered'
	}, {
		list: 'bullet'
	}],
	[{
		direction: 'rtl'
	}],
	[{
		align: []
	}],
	['link', 'image'],
];

const handlers = {
	image() {
		let self = this;
		let fileInput = this.container.querySelector('input.ql-image[type=file]');
		if (fileInput === null) {
			fileInput = document.createElement('input');
			fileInput.setAttribute('type', 'file');
			// 设置图片参数名
			if ('img') {
				fileInput.setAttribute('name', 'img');
			}
			// 设置上传图片的格式
			fileInput.setAttribute('accept', 'image/png, image/jpg, image/jpeg');
			fileInput.classList.add('ql-image');
			// 监听选择文件
			fileInput.addEventListener('change', function () {
				// 创建formData
				let formData = new FormData();
				formData.append('file', fileInput.files[0]);
				fileInput.value = '';
				axios.post('/api/blog/common/', formData)
					.then(res => {
						let length = self.quill.getSelection(true).index;
						self.quill.insertEmbed(length, 'image', res.data);
						self.quill.setSelection(length + 1)
						fileInput.value = ''
					}).catch(err => console.log('err :', err));
			});
			this.container.appendChild(fileInput);
		}
		fileInput.click();
	}
};

export const Bubble = {
	placeholder: '有什么想和大家分享的？',
	theme: 'bubble',
	mixins: [getBasicInfo],
	modules: {
		toolbar: {
			container: toolOptions, // 工具栏选项
			handlers: handlers // 事件重写
		}
	}
}

export default {
	placeholder: '有什么想和大家分享的？',
	theme: 'snow',
	mixins: [getBasicInfo],
	modules: {
		toolbar: {
			container: toolOptions, // 工具栏选项
			handlers: handlers // 事件重写
		}
	}
};